import React from 'react'
import { Toast } from 'antd-mobile'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import { actions as listActionCraetors } from '../../redux/modules/list'
import ComplexCustomOverlay from './customOverlay'
import './map.less';

class Map extends React.PureComponent {

  static contextTypes = {
    router: React.PropTypes.object.isRequired
  }

  state = {
    data: [],
    active: -1
  }

  componentDidMount() {
    this.map = new BMap.Map('container');
    this.map.enableScrollWheelZoom();
    this.map.enableInertialDragging();
    this.map.enableContinuousZoom();
    new BMap.LocalCity().get(result => {
      this.map.centerAndZoom(new BMap.Point(result.center.lng, result.center.lat), 10);
      this.fetchPos()
    })
  }

  render() {
    const visible = this.props.params.type == 'true' && this.state.data.length > 0
    return <section className="page-wrap">
      <div id="container" style={{height: visible ? '60%': '100%'}}></div>
      {
        visible && <div className='list-wrap'>
        {
          this.state.data.map((item, index) => {
            return <div className={this.state.active == index ? 'item active' : 'item'} key={index}>
              <div className='no'><text>{index + 1}</text></div>
              <div className='content'>
                <div><text>地址：</text>{item.location || ''}</div>
                <div><text>时间：</text>{item.lastTime || ''}</div>
              </div>
            </div>
          })
        }
        </div>
      }
    </section>
  }

  initMap(data, type) {
    if (type == 'false') {
      this.position(data[0])
    } else{
      this.trail(data)
    }
  }

  tagCustomOverlay(point, index) {
    var compOverlay = new ComplexCustomOverlay(this.map, point, `
      <div style="width: 30px; text-align:center">${index}</div>` , {
      'width': '30px',
      'text-align': 'left',
      'background': 'transparent',
      'line-height': '18px',
      'font-size': '12px',
      'border-radius': 'none',
      'margin-top': '-23px',
      'margin-left': '-17px'
    });
    this.map.addOverlay(compOverlay);  
  }

  posCustomOverlay(point, data) {
    this.myCompOverlay = new ComplexCustomOverlay(this.map, point, `
      <div style="width: 190px; padding: 5px">
      车牌：${data.carMark} <br> 
      地点：${data.location} <br> 
      时间：${data.lastTime}</div>` , {
      'width': '200px',
      'background': 'rgba(0, 0, 0, .8)',
      'border': '1px solid #ccc',
      'border-radius': 'none',
      'text-align': 'left',
      'line-height': '18px',
      'font-size': '12px',
      'margin-top': '-109px',
      'margin-left': '-100px'
    });
    this.map.addOverlay(this.myCompOverlay);  
  }
  
  drawTrail(data, color) {
    let pos = []
    data.map(item => {
      var point = new BMap.Point(item.last_lon, item.last_lat)
      var marker = new BMap.Marker(point);
      pos.push(point)
      this.map.addOverlay(marker);
    })

    var polyline = new BMap.Polyline(pos, {
      enableEditing: false, //是否启用线编辑，默认为false
      enableClicking: true, //是否响应点击事件，默认为true
      strokeWeight:'8', //折线的宽度，以像素为单位
      strokeOpacity: 0.8, //折线的透明度，取值范围0 - 1
      strokeColor: color  //折线颜色
    });

    this.map.addOverlay(polyline);          //增加折线
  }

  trail(data) {
    var lngs = data.map(item => +item.last_lon).sort()
    var lats = data.map(item => +item.last_lat).sort()
    var avg_lng = (lngs[lngs.length - 1] + lngs[0]) / 2
    var avg_lat = (lats[lats.length - 1] + lats[0]) / 2

    this.go_arr = data.filter(item => item.CarSectionType == 0)
    this.back_arr = data.filter(item => item.CarSectionType == 1)
    
    this.map.centerAndZoom(new BMap.Point(avg_lng, avg_lat), 10);

    this.drawTrail(this.go_arr, '#18a45b')
    this.drawTrail(this.back_arr, '#f30')

    data.forEach((item, index) => {
      var point = new BMap.Point(item.last_lon, item.last_lat)
      this.tagCustomOverlay(point,index + 1)
    })
  }

  position(data) {
    var point = new BMap.Point(+data.last_lon, +data.last_lat)
    var marker = new BMap.Marker(point);
    this.map.centerAndZoom(point, 10);
    this.map.addOverlay(marker);  
    this.posCustomOverlay(point, data)
  }

  fetchPos() {
    Toast.loading('数据请求中...', 100);
    const { carNo, orderNo, type } = this.props.params
    this.props.actions.fetchPosition({
      carNo, 
      orderNo, 
      type
    }, json => {
      if (json.IsSuccess) {
        Toast.hide()
        this.setState({
          data: json.Data
        }, () => {
          setTimeout(() => {
            this.initMap(json.Data, type)  
          }, 500)
        })
      } else {
        Toast.fail(json.Msg, 1);
      }
    })
  }
}

const stateToProps = state => ({
  ...state.list
})

const dispatchToProps = dispatch => ({
  actions: bindActionCreators(listActionCraetors, dispatch)
})

export default connect(stateToProps, dispatchToProps)(Map);
